<!-- 孔德嘉  用户 -->
<template>
  <div id="CarSharingUser">
    <el-card style="margin-bottom: 10px">
      <el-input
        v-model="userName"
        style="width: 200px"
        placeholder="请输入用户名"
        suffix-icon="el-icon-message"
      ></el-input>
      <el-button
        class="custom-button ml-10"
        icon="el-icon-search"
        @click="queryUserByName()"
        >搜索</el-button
      >
      <el-button
        style="margin-left: 30px"
        class="custom-buttonT"
        icon="el-icon-plus"
        functionCode="user:add"
        @click="openAddWindow">添加</el-button
      >
    </el-card>
    <!-- 表格 -->
    <el-card>
      <el-table :data="userData" border stripe height="600">
        <el-table-column fixed label="头像">
          <template slot-scope="scope">
            <el-avatar
              size="medium"
              :src="
                $imageUrl + scope.row.avatarId"
            ></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名"></el-table-column>
        <el-table-column prop="loginName" label="登录名"></el-table-column>
        <el-table-column
          prop="email"
          label="管理员邮箱"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="phone"
          label="手机号"
          min-width="140"
        ></el-table-column>
        <el-table-column
          prop="age"
          label="年龄"
          min-width="60"
        ></el-table-column>
        <el-table-column
          functionCode="user:update"
          label="状态"
          min-width="150"
        >
          <template slot-scope="scope">
            <el-radio-group
              @input="aaaain(scope.row)"
              size="small"
              v-model="scope.row.userFlag"
            >
              <el-radio-button :label="0">启用</el-radio-button>
              <el-radio-button :label="1">禁用</el-radio-button>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column
          prop="lastLoginTime"
          label="最后登录时间"
          min-width="200"
        ></el-table-column>
        <el-table-column
          prop="lastLoginIp"
          label="最后登录ip"
          min-width="120"
        ></el-table-column>

        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="180"
        ></el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              class="text_button"
              functionCode="user:empower"
              @click="opsouquanshow(scope.row)"
              icon="el-icon-coordinate"
              type="text"
              >授权
            </el-button>
            <el-button
              class="text_button"
              functionCode="user:update"
              @click="openUserInfoWindow(scope.row, 'updateInfo')"
              icon="el-icon-edit"
              type="text"
              >编辑
            </el-button>
            <!-- <el-button
              class="text_button"
              functionCode="user:logoff"
              @click="deleteUserById(scope.row.id)"
              icon="el-icon-delete"
              type="text"
              >注销</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      class="pageAll"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="text-align: center"
    >
    </el-pagination>
    <!-- 添加弹出框 -->
    <el-dialog title="授权菜单" :visible.sync="souquanshow" width="30%">
      <el-tree
        :default-checked-keys="defaultchecked"
        ref="tree"
        :data="selectmenulist"
        show-checkbox
        node-key="id"
        :props="{ children: 'children', label: 'title' }"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="souquanshow = false">取 消</el-button>
        <el-button type="primary" @click="souquan">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加员工信息" :visible.sync="userAddWindow" width="30%">
      <el-form
        :model="userForm"
        ref="userForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img
              height="200"
              width="200"
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
          <el-input v-model="userForm.loginName"></el-input>
        </el-form-item>
        <el-form-item label="管理员邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input type="number" v-model="userForm.age"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userAddWindow = false">取 消</el-button>
        <el-button type="primary" @click="addUserInfo('userForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 详情弹出框 -->
    <el-dialog
      title="修改病虫害信息"
      :visible.sync="userInfoWindow"
      width="30%"
    >
      <el-form
        :model="userInfo"
        ref="userForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img
              height="200"
              width="200"
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userInfo.userName"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="loginName">
          <el-input v-model="userInfo.loginName"></el-input>
        </el-form-item>
        <el-form-item label="管理员邮箱" prop="email">
          <el-input v-model="userInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userInfo.phone"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input type="number" v-model="userInfo.age"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userInfoWindow = false">取 消</el-button>
        <el-button
          @click="updateUserInfo('userForm')"
          :disabled="disable"
          type="primary"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "CarSharingUser",
  data() {
    return {
      souquanshow: false,
      souquanid: 0,
      defaultchecked: [],
      disable: true,
      userName: "", // 用户姓名
      userData: [], // 员工查询数据
      userAddWindow: false, // 员工添加窗口控制
      userInfoWindow: false, // 员工信息窗口控制
      selectmenulist: [],
      userForm: {
        // 员工添加对象
        userName: "", // 员工名称
        age: "", // 年龄
        address: 1, // 地址
        email: "", // 邮箱
      },
      imageUrl: "",
      file: "",
      userInfo: {}, // 员工信息
      pageSize: 5, // 每页显示的个数
      pageNum: 1, // 起始的页数 表格中当前页面
      total: 0,
    };
  },
  mounted() {
    // 查询 菜单
    this.$axios
      .get("sysMenu/getMenuByUser")
      .then((res) => {
        if (res.status === 200) {
          this.selectmenulist = res.data.data;
        }
      })
      .catch((error) => {
      });
    this.queryUserByName();
  },
  methods: {
    souquan() {
      const menuIds = this.$refs.tree.getCheckedNodes(false, true);
      const formdata = new FormData();
      formdata.set("userId", this.souquanid);
      for (const a in menuIds) {
        formdata.append("menuIds", menuIds[a].id);
      }
      this.$axios.post("sysUser/userPower", formdata).then((res) => {
        this.myMessage("success", "授权成功");
        this.souquanshow = false;
      });
    },
    opsouquanshow(row) {
      this.$axios.get("sysUser/getUserPower?userId=" + row.id).then((res) => {
        const bb = [];
        res.data.data.forEach((a) => {
          const node = this.$refs.tree.getNode(a).data;
          if (node.children.length === 0) {
            bb.push(a);
          }
        });
        this.defaultchecked = bb;
        // this.$refs.tree.setCheckedKeys(res.data.data,true)
      });
      this.souquanid = row.id;
      this.souquanshow = true;
    },
    aaaain(a) {
      this.userInfo = {};
      this.userInfo.id = a.id;
      this.userInfo.userFlag = a.userFlag;
      this.updateUserInfo();
    },
    beforeAvatarUpload(file) {
      // 上传log图片格式
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("上传logo图片只能是JPG/PNG格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      // 赋值
      this.file = file;
      this.imageUrl = URL.createObjectURL(file);
      // isJPG && isLt2M 自动提交 false 是点击确定后提交
      return false;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.queryUserByName();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.queryUserByName();
    },
    updateUserInfo (formName) {
          var formdata = new FormData()
            for(var a in this.userInfo){
                if(this.userInfo[a]!=null){
                    formdata.set(a,this.userInfo[a])
                }
            }
            if(this.file){
                formdata.set('avatar',this.file,this.file.filename)
            }
            this.$axios
              .put(
                'sysUser/updateUserByPc',
                formdata    
              )
              .then((res) => {
                if (res.status === 200) {
                  this.myMessage('success', '恭喜您！成功修改了一条信息！')
                  this.userInfoWindow = false
                  this.queryUserByName()
                } else {
                  this.myMessage('warning', '警告喔！您有一条信息修改失败！')
                }
              })
      },
    openUserInfoWindow(row, windowType) {
      // 打开修改或详情窗口
      this.userInfo = JSON.parse(JSON.stringify(row));
      this.disable = windowType === "getInfo";
      this.imageUrl =  this.$imageUrl +
        this.userInfo.avatarId;
      this.file = "";
      this.userInfoWindow = true;
    },
    deleteUserById(id) {
      // 删除信息
      this.$confirm("此操作将注销该员工信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
        
          this.userInfo = {};
          this.userInfo.id = id;
          this.userInfo.userFlag = 1;
          this.updateUserInfo();
        })
        .catch((error) => {
          this.myMessage("info", "已取消");
        });
    },
    queryUserByName() {
      // 查询员工信息
      this.$axios
        .get("sysUser/getUserByPage", {
          params: {
            userName: this.userName,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
          },
        })
        .then((res) => {
          if (res.status === 200) {
            this.userData = res.data.data.content;
            this.total = res.data.data.totalSize;
            
          }
        })
        .catch((error) => {
          this.myMessage("error", "错误哦！系统错误，请联系管理员！");
        });
    },
    addUserInfo(formName) {
      // 添加
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formdata = new FormData();
          for (const a in this.userForm) {
            if (this.userForm[a]) {
              formdata.set(a, this.userForm[a]);
            }
          }
          if (this.file) {
            formdata.set("avatar", this.file, this.file.filename);
          }
          this.$axios
            .post("sysUser/saveUser", formdata)
            .then((res) => {
              if (res.status === 200) {
                this.myMessage("success", "恭喜您！成功添加了一条信息！");
                this.userAddWindow = false;
                this.$refs[formName].resetFields();
                this.queryUserByName();
              } else {
                this.myMessage("warning", "警告喔！您有一条信息添加失败！");
              }
            })
            .catch((error) => {
              this.myMessage("error", "错误哦！系统错误，请联系管理员！");
            });
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //打开添加窗口
    openAddWindow() {
      this.file = "";
      let a = window.localStorage.getItem("user");
      this.userForm.createUser = window.localStorage.getItem("userId");
      this.userForm.updateUser = window.localStorage.getItem("userId");
      // 打开添加窗口
      this.userAddWindow = true;
    },
    // 提示信息
    myMessage(type, message) {
      this.$message({
        showClose: true,
        message: message,
        type: type,
      });
    },
    // 表格文字居中

    // 过滤树
    filterNode(value, data) {
      if (!value) return true;
      return data.menuName.indexOf(value) !== -1;
    },
  },
};
</script>

  <style lang="less" scoped>
#ul1 {
  height: 40px;
  margin-bottom: 15px;
  list-style: none;
}
#ul1 li {
  float: left;
  margin-right: 10px;
}
</style>
